package com.wan.data.mysql.orm.convert.auto;

import com.wan.data.mysql.orm.convert.AutoConverter;
import com.wan.data.mysql.orm.meta.ColumnMeta;
import com.wan.data.mysql.util.DbColumnType;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.ZoneId;

/**
 * 时间类型处理，入库统一使用datetime类型
 */
public class DateTimeConverter implements AutoConverter {
    @Override
    public Class<?>[] convertType() {
        return new Class[]{java.util.Date.class, java.sql.Date.class, LocalDateTime.class, Timestamp.class};
    }

    @Override
    public DbColumnType getDbType() {
        return DbColumnType.DATETIME;
    }

    @Override
    public Object dbToEntity(ColumnMeta columnMeta, Object value) throws Exception {
        Class<?> fieldType = columnMeta.getFieldType();
        LocalDateTime localDateTime = (LocalDateTime) value;
        Object castValue = localDateTime;
        if (fieldType == java.util.Date.class) {
            castValue = java.util.Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        } else if (fieldType == java.sql.Date.class) {
            castValue = java.sql.Date.valueOf(localDateTime.toLocalDate());
        } else if (fieldType == Timestamp.class) {
            castValue = Timestamp.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        }
        return castValue;
    }

    @Override
    public Object entityToDb(ColumnMeta columnMeta, Object value) throws Exception {
        Class<?> fieldType = columnMeta.getFieldType();
        if (fieldType == java.util.Date.class) {
            return LocalDateTime.ofInstant(((java.util.Date) value).toInstant(),
                    ZoneId.systemDefault());
        } else if (fieldType == java.sql.Date.class) {
            return ((java.sql.Date) value).toLocalDate().atTime(java.time.LocalTime.now(ZoneId.systemDefault()));
        } else if (fieldType == Timestamp.class) {
            return ((Timestamp) value).toLocalDateTime();
        }
        return value;
    }
}
